package com.matrix.draft.sockettest.day7;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

import java.nio.ByteBuffer;

/**
 * 该Handler专门处理IdleStateHandler发过来的心跳检测包
 */
public class HeartBeatHandler extends SimpleChannelInboundHandler<ByteBuffer> {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 判断这个evt是什么类型的事件
        if (evt instanceof IdleStateEvent) {
            // 强转成真实事件类型
            IdleStateEvent idleEvent = (IdleStateEvent) evt;
            String state = "未知空闲";
            // 判断心跳状态
            // idleEvent.state()可能返回三种: READER_IDLE(读空闲),WRITER_IDLE(写空闲),ALL_IDLE(都空闲)
            switch (idleEvent.state()) {
                case READER_IDLE:
                    state = "读空闲";
                    break;
                case WRITER_IDLE:
                    state = "写空闲";
                    break;
                case ALL_IDLE:
                    state = "读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + state);
            ctx.close(); // 发送空闲事件后关闭通道
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuffer msg) throws Exception {

    }
}
